package com.oriole.api.module.sys.service.impl;

import com.oriole.api.config.quartz.util.CronUtils;
import com.oriole.api.config.quartz.util.ScheduleUtils;
import com.oriole.api.module.sys.repository.SysJobRepository;
import com.oriole.api.module.sys.service.ISysJobService;
import com.oriole.common.constant.ScheduleConstants;
import com.oriole.common.exception.TaskException;
import com.oriole.common.util.ConvertUtil;
import com.oriole.entity.sys.SysJob;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/9/20 22:46
 * description:
 */
@Service
public class SysJobServiceImpl implements ISysJobService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private SysJobRepository sysJobRepository;

    /**
     * 项目启动时，初始化定时器
     * 主要是防止手动修改数据库导致未同步到定时任务处理
     * （注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> sysJobs = sysJobRepository.findAll();
        for (SysJob job : sysJobs) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Override
    public SysJob findById(Long id) {
        return sysJobRepository.findById(id).orElse(new SysJob());
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        sysJobRepository.save(job);
        scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        sysJobRepository.save(job);
        scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        sysJobRepository.deleteById(jobId);
        scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void deleteJobByIds(String ids) throws SchedulerException {
        Long[] jobIds = ConvertUtil.toLongArray(ids);
        for (Long jobId : jobIds) {
            SysJob job = sysJobRepository.findById(jobId).orElse(new SysJob());
            deleteJob(job);
        }
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void changeStatus(SysJob job) throws SchedulerException {
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            pauseJob(job);
        }
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public void run(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        SysJob tmpObj = findById(job.getId());
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, tmpObj);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, tmpObj.getJobGroup()), dataMap);
    }

    @Override
    @Transactional(rollbackFor = {SchedulerException.class, TaskException.class})
    public void saveJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        sysJobRepository.save(job);
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    @Override
    @Transactional(rollbackFor = {SchedulerException.class, TaskException.class})
    public void updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = findById(job.getId());
        sysJobRepository.save(job);

        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, properties.getJobGroup());
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }
}